import { useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import './VideoDetail.css';

// 假数据，可扩展更多视频
const initialVideoList = [
  {
    id: '1',
    avatar: 'https://randomuser.me/api/portraits/women/44.jpg',
    username: '滑板鞋',
    likes: 176,
    comments: 1768,
    shares: 25,
    video: 'https://www.w3schools.com/html/movie.mp4',
    desc: '弹弓真好，声音震撼',
    music: '晴天',
    userAvatar: 'https://randomuser.me/api/portraits/women/44.jpg',
    isFollow: false,
    liked: false,
    commentList: ["好棒！", "视频很赞"]
  },
  {
    id: '2',
    avatar: 'https://randomuser.me/api/portraits/men/32.jpg',
    username: '滑板哥',
    likes: 200,
    comments: 888,
    shares: 30,
    video: 'https://www.w3schools.com/html/mov_bbb.mp4',
    desc: '滑板真帅',
    music: '夜空中最亮的星',
    userAvatar: 'https://randomuser.me/api/portraits/men/32.jpg',
    isFollow: true,
    liked: false,
    commentList: ["666", "太酷了"]
  },
  {
    id: '3',
    avatar: 'https://randomuser.me/api/portraits/men/45.jpg',
    username: '极限玩家',
    likes: 321,
    comments: 123,
    shares: 12,
    video: 'https://www.w3schools.com/html/mov_bbb.mp4',
    desc: '极限运动，挑战自我',
    music: '极限青春',
    userAvatar: 'https://randomuser.me/api/portraits/men/45.jpg',
    isFollow: false,
    liked: false,
    commentList: ["太刺激了！"]
  },
  {
    id: '4',
    avatar: 'https://randomuser.me/api/portraits/women/33.jpg',
    username: '美食家',
    likes: 512,
    comments: 256,
    shares: 40,
    video: 'https://www.w3schools.com/html/movie.mp4',
    desc: '美食分享，快乐生活',
    music: '美味人生',
    userAvatar: 'https://randomuser.me/api/portraits/women/33.jpg',
    isFollow: true,
    liked: false,
    commentList: ["看饿了！", "求做法"]
  },
  {
    id: '5',
    avatar: 'https://randomuser.me/api/portraits/men/22.jpg',
    username: '旅行者',
    likes: 789,
    comments: 333,
    shares: 55,
    video: 'https://www.w3schools.com/html/movie.mp4',
    desc: '世界那么大，我想去看看',
    music: '旅途',
    userAvatar: 'https://randomuser.me/api/portraits/men/22.jpg',
    isFollow: false,
    liked: false,
    commentList: ["风景真美", "羡慕！"]
  },
  // 新增短视频类型
  {
    id: '6',
    avatar: 'https://randomuser.me/api/portraits/women/55.jpg',
    username: '短视频达人',
    likes: 120,
    comments: 45,
    shares: 10,
    video: 'https://www.w3schools.com/html/movie.mp4',
    desc: '15秒短视频，记录美好瞬间',
    music: '短暂的美好',
    userAvatar: 'https://randomuser.me/api/portraits/women/55.jpg',
    isFollow: false,
    liked: false,
    commentList: ["短视频也精彩！"]
  },
  // 新增风景类型
  {
    id: '7',
    avatar: 'https://randomuser.me/api/portraits/men/77.jpg',
    username: '风景控',
    likes: 999,
    comments: 500,
    shares: 80,
    video: 'https://www.w3schools.com/html/mov_bbb.mp4',
    desc: '祖国大好河山，美不胜收',
    music: '山水之间',
    userAvatar: 'https://randomuser.me/api/portraits/men/77.jpg',
    isFollow: true,
    liked: false,
    commentList: ["太美了", "想去旅行"]
  },
  // 新增搞笑类型
  {
    id: '8',
    avatar: 'https://randomuser.me/api/portraits/men/88.jpg',
    username: '搞笑小王',
    likes: 666,
    comments: 222,
    shares: 66,
    video: 'https://www.w3schools.com/html/movie.mp4',
    desc: '笑一笑，十年少！',
    music: '快乐每一天',
    userAvatar: 'https://randomuser.me/api/portraits/men/88.jpg',
    isFollow: false,
    liked: false,
    commentList: ["哈哈哈", "太逗了"]
  }
];

export default function VideoDetail() {
  const navigate = useNavigate();
  const [videoList, setVideoList] = useState(initialVideoList);
  const [current, setCurrent] = useState(0);
  const [loading, setLoading] = useState(false);
  const [hasMore, setHasMore] = useState(true);
  const [showComment, setShowComment] = useState(false);
  const [commentInput, setCommentInput] = useState("");
  const startY = useRef(null);
  
  // 返回主页
  const goToHomepage = () => {
    navigate('/homepage');
  };

  // 鼠标按下
  const handleMouseDown = (e) => {
    startY.current = e.clientY;
    window.addEventListener("mousemove", handleMouseMove);
    window.addEventListener("mouseup", handleMouseUp);
  };

  // 拖动
  const handleMouseMove = () => {};

  // 松开
  const handleMouseUp = (e) => {
    window.removeEventListener("mousemove", handleMouseMove);
    window.removeEventListener("mouseup", handleMouseUp);
    if (startY.current === null) return;
    const deltaY = e.clientY - startY.current;
    console.log('mouseup', deltaY, 'current:', current);
    if (deltaY > 80) {
      handleNext();
    } else if (deltaY < -80 && current > 0) {
      setCurrent(current - 1);
    }
    startY.current = null;
  };

  // 触摸开始
  const handleTouchStart = (e) => {
    startY.current = e.touches[0].clientY;
  };
  // 触摸结束
  const handleTouchEnd = (e) => {
    if (startY.current === null) return;
    const endY = e.changedTouches[0].clientY;
    const deltaY = endY - startY.current;
    if (deltaY > 80) {
      handleNext();
    } else if (deltaY < -80 && current > 0) {
      setCurrent(current - 1);
    }
    startY.current = null;
  };

  // 处理下一个视频逻辑
  const handleNext = () => {
    if (current < videoList.length - 1) {
      setCurrent(current + 1);
    } else if (hasMore && !loading) {
      setLoading(true);
      // 模拟异步加载
      setTimeout(() => {
        // 假设没有更多数据了
        setHasMore(false);
        setLoading(false);
      }, 1500);
    }
  };

  // 点赞操作
  const handleLike = () => {
    setVideoList(list => list.map((v, idx) =>
      idx === current
        ? {
            ...v,
            liked: !v.liked,
            likes: v.liked ? v.likes - 1 : v.likes + 1
          }
        : v
    ));
  };

  // 评论操作
  const handleComment = () => {
    setShowComment(true);
  };
  const handleCommentSubmit = (e) => {
    e.preventDefault();
    if (!commentInput.trim()) return;
    setVideoList(list => list.map((v, idx) =>
      idx === current
        ? {
            ...v,
            comments: v.comments + 1,
            commentList: [...v.commentList, commentInput.trim()]
          }
        : v
    ));
    setCommentInput("");
    // setShowComment(false); // 不关闭弹窗，便于连续评论
  };

  const video = videoList[current];

  return (
    <div
      className="video-detail-page"
      style={{
        overflow: "hidden",
        height: "100vh",
        width: "100vw",
        userSelect: "none",
        position: "fixed",
        top: 0, left: 0, right: 0, bottom: 0,
        background: "#000",
        zIndex: 9999
      }}
      onMouseDown={handleMouseDown}
      onTouchStart={handleTouchStart}
      onTouchEnd={handleTouchEnd}
    >
      <div style={{ width: "100%", height: "100vh", position: "relative" }}>
        <video
          className="video-player"
          src={video.video}
          controls
          autoPlay
          loop
          style={{ width: "100%", height: "100%", objectFit: "cover", pointerEvents: "none" }}
        />
        <div className="video-detail-sidebar">

          
          <div className="icon-group">
            <div className="icon-item" onClick={handleLike} style={{cursor:'pointer'}}>
              <span className="icon" style={{color: video.liked ? 'red' : '#fff'}}>{video.liked ? '♥' : '♡'}</span>
              <span className="icon-text">{video.likes}</span>
            </div>
            <div className="icon-item" onClick={handleComment} style={{cursor:'pointer'}}>
              <span className="icon">💬</span>
              <span className="icon-text">{video.comments}</span>
            </div>
            <div className="icon-item">
              <span className="icon">↗</span>
              <span className="icon-text">{video.shares}</span>
            </div>
          </div>
        </div>
        <div className="video-detail-bottom">
          <img className="avatar" src={video.avatar} alt="avatar" />
          <span className="username">{video.username}</span>
          <button className="follow-btn">关注</button>
          <div className="desc">{video.desc}</div>
          <div className="music">🎵 {video.music}</div>
        </div>
        <img className="corner-avatar" src={video.userAvatar} alt="corner-avatar" />
        {loading && (
          <div style={{
            position: "absolute",
            bottom: 80,
            left: 0,
            width: "100%",
            textAlign: "center",
            color: "#fff",
            fontSize: 20,
            fontWeight: "bold"
          }}>
            加载中...
          </div>
        )}
        {!hasMore && !loading && current === videoList.length - 1 && (
          <div style={{
            position: "absolute",
            bottom: 80,
            left: 0,
            width: "100%",
            textAlign: "center",
            color: "#fff",
            fontSize: 20,
            fontWeight: "bold"
          }}>
            没有更多了
          </div>
        )}
        {/* 评论弹窗 */}
        {showComment && (
          <div className="comment-modal">
            <div className="comment-panel">
              <button className="comment-close" onClick={()=>setShowComment(false)}>×</button>
              <div className="comment-panel-header">评论</div>
              <div className="comment-list">
                {video.commentList.length === 0 && <div className="comment-empty">暂无评论</div>}
                {video.commentList.map((c, i) => (
                  <div key={i} className="comment-item">{c}</div>
                ))}
              </div>
              <form className="comment-input-bar" onSubmit={handleCommentSubmit}>
                <input
                  value={commentInput}
                  onChange={e=>setCommentInput(e.target.value)}
                  placeholder="留下你的精彩评论..."
                  autoFocus
                />
                <button type="submit">发送</button>
              </form>
              <button
                style={{
                  width: "90%",
                  margin: "16px auto 8px auto",
                  display: "block",
                  background: "#f5f5f5",
                  color: "#333",
                  border: "none",
                  borderRadius: "16px",
                  padding: "10px 0",
                  fontSize: "16px",
                  cursor: "pointer"
                }}
                onClick={() => setShowComment(false)}
              >
                关闭评论
              </button>
            </div>
          </div>
        )}
      </div>
      <button className="back-btn" onClick={() => navigate(-1)}>&lt;</button>
      <button className="home-btn" onClick={goToHomepage}>首页</button>
    </div>
  );
} 